package com.thread.sync.sync11;

import java.util.Random;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class Runner implements Runnable {
    /**
     * 必须所有线程都执行完相应的操作,才会继续各自往下执行,
     * 好比跑步比赛,所有运动员都准备就绪才能开始比赛,开始所有人都一起跑
     */
    private CyclicBarrier barrier;
    private String name;

    public Runner(CyclicBarrier barrier, String name) {
        this.barrier = barrier;
        this.name = name;
    }

    @Override
    public void run() {
        try {
            Thread.sleep(1000 * (new Random()).nextInt(5));//准备
            System.out.println(name + " 准备OK.");
            barrier.await();  //停止监听,所有线程都准备好才继续
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println(name + " Go!!");
    }

    public static void main(String[] args) {
        CyclicBarrier barrier = new CyclicBarrier(3);  // 3 :表示一共3个线程,即3个都开启再一起执行
        ExecutorService executor = Executors.newFixedThreadPool(3);
        //三个线程都启动之后才会继续往await下执行
        executor.submit(new Thread(new Runner(barrier, "姚振")));
        executor.submit(new Thread(new Runner(barrier, "何毅")));
        executor.submit(new Thread(new Runner(barrier, "崔杰")));
        executor.shutdown();
    }
}
